<template>
  <div>
    <h1>添加节点测试</h1>

    <el-button type="" @click="addCustom1">添加节点</el-button>
    <el-button type="" @click="showData">显示数据结构</el-button>
    <div id="container8">
    </div>

  </div>
</template>

<script>
import dataObj from "@/mock/baseData.js";
import tabModFn from "@/components/mod/html/tabMod";
import { Graph, Node, Shape } from "@antv/x6";
import x6MainFn from "@/components/mod/x6Main/index.js";
const { DagreLayout } = window.layout;
var graph = {};
var nodeObjTypeList = ["tab", "node"];
var mainFn = {};
var Nodes = [];
var Edges = [];
export default {
  data() {
    return {
      graph: "",
      rootId: "",
      data:{}
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    showData() {
      console.log("getCells()", this.graph.getCells());
      console.log("getNodes()", this.graph.getNodes());
      console.log("toJSON()", this.graph.toJSON());
    },
    addCustom1(typeStr) {
      let startNode = {};
      let selectNode = graph.getSelectedCells();

      if (
        selectNode &&
        selectNode.length == 1 &&
        selectNode.data &&
        nodeObjTypeList.indexOf(selectNode.data.type) > -1
      ) {
        selectNode = selectNode[0];
      } else {
        //选择默认rootId;
        selectNode = mainFn.getRootNode();
      }
      console.log("selectNodeId: ", selectNode.id);

      // let nodes = mainFn.getNodes();
      // console.log("nodes: ", nodes);
      /* nodes.map((node) => {
        console.log("flag: ", this.graph.isRootNode(node));
      }); */
      let id = new Date().toString()
      let nodeObj = {
        id: id,
        width: 344,
        height: 234,
        shape: "html",
        data: {
          time: new Date().toString(),
          type: "tab",
          rootId: "001",
          title: "我是新表名",
          text: [
            {
              英文名: "end",
              中文: "cn",
              英文长表名名: "eddddddddddddddddddddddddddddddddnd312312dsdas",
              uuid: "e12n33dsadddddfffffffffew",
            },
          ],
        },
        html: {
          render(node) {
            const data = node.getData();
            console.log("render  data", data);
            return tabModFn(data);
          },
          shouldComponentUpdate(node) {
            // 控制节点重新渲染
            return node.hasChanged("data");
          },
        },
      }
      // const child = this.graph.addNode(nodeObj);
      console.log("selectNode", selectNode);
      // selectNode.addChild(child);
      console.log("this.data")
      this.data.nodes.push(nodeObj);
      let edgeObj = {
        shape: "edge", // 指定使用何种图形，默认值为 'edge'
        source: selectNode.id,
        target: nodeObj.id,
      }
      // this.graph.addEdge(edgeObj);
      this.data.edges.push(edgeObj);

      // console.log("model getOutgoingEdges", this.graph.getOutgoingEdges("001"));

      // let cell = mainFn.getById(selectNode.id);
      // console.log("cell", cell);

      // cell.addChild(child);
      // cell.setChildren(child);
      /* if (cell.children) {
        cell.children.push(child);
      } else {
        cell.children = [child];
      } */

      let nodes = mainFn.getNodes();
      let edges = this.graph.getEdges();
      let model = { nodes, edges };

      console.log("model", this.data);
      this.graph.freeze();
      const dagreLayout = new DagreLayout({
        type: "dagre",
        rankdir: "LR",
        align: "",
        ranksep: 30,
        nodesep: 30,
        controlPoints: true,
      });
      let arr = { nodes: [], edges: [] };

      let Model = this.graph.parseJSON(this.graph.toJSON());
      for (let index = 0; index < Model.length; index++) {
        const item = Model[index];
        item.shape == "edge"
          ? arr.edges.push({
              shape: "edge",
              source: item.source.cell,
              target: item.target.cell,
            })
          : arr.nodes.push(item);
      }

      console.log("arr", arr);
      const newModel = dagreLayout.layout(this.data);
      graph.fromJSON(newModel);
       this.graph.unfreeze()
    },
    dataInit() {
      this.rootId = "001";
      /* this.graph.addNode({
        id: "001",
        width: 344,
        height: 234,
        shape: "html",
        data: {
          time: new Date().toString(),
          type: "tab",
          rootId: "001",
          title: "我是大表名",
          text: [
            {
              英文名: "end",
              中文: "cn",
              英文长表名名: "eddddddddddddddddddddddddddddddddnd312312dsdas",
              uuid: "e12n33dsadddddfffffffffew",
            },
          ],
        },
        html: {
          render(node) {
            const data = node.getData();
            console.log("render  data", data);
            return tabModFn(data);
          },
          shouldComponentUpdate(node) {
            // 控制节点重新渲染
            return node.hasChanged("data");
          },
        },
      }); */
      let nodes = [
        {
          id: "001",
          width: 344,
          height: 234,
          shape: "html",
          children: [],
          data: {
            time: new Date().toString(),
            type: "tab",
            rootId: "001",
            title: "我是大表名",
            text: [
              {
                英文名: "end",
                中文: "cn",
                英文长表名名: "eddddddddddddddddddddddddddddddddnd312312dsdas",
                uuid: "e12n33dsadddddfffffffffew",
              },
            ],
          },
          html: {
            render(node) {
              const data = node.getData();
              console.log("render  data", data);
              return tabModFn(data);
            },
            shouldComponentUpdate(node) {
              // 控制节点重新渲染
              return node.hasChanged("data");
            },
          },
        },
      ];

      let model = { nodes, edges: [] };
      let newnode = {...model.nodes[0]};
      newnode.id = "002"
      model.nodes.push(newnode);
      model.edges.push({ shape: "edge", // 指定使用何种图形，默认值为 'edge'
        source: "001",
        target: newnode.id });
      const dagreLayout = new DagreLayout({
        type: "dagre",
        rankdir: "LR",
        align: "",
        ranksep: 150,
        nodesep: 150,
        controlPoints: true,
      });
      this.data = model;
      console.log("model",model)
      const newModel = dagreLayout.layout(model);
      graph.fromJSON(newModel);
    },
    init() {
      let width = document.body.clientWidth; //网页可见区域宽：
      let height = document.body.clientHeight; //网页可见区域高：
      // 渲染画布
      graph = new Graph({
        container: document.getElementById("container8"),
        width,
        height: 900,
        panning: {
          enabled: false, //画布可以平移
          //还可以配置 eventTypes 来设置触发画布拖拽的行为，支持 leftMouseDown、 rightMouseDown、mouseWheel，默认为 ['leftMouseDown'] 。
          eventTypes: ["leftMouseDown", "rightMouseDown", "mouseWheel"],
        },
        interacting: { nodeMovable: false },
        async: true,
        // frozen: true,
        background: {
          color: "#fffbe6", // 设置画布背景颜色
        },
        grid: {
          size: 10, // 网格大小 10px
          visible: true, // 渲染网格背景
        },
        selecting: {
          enabled: true,
          // rubberband: true,
          showNodeSelectionBox: true,
        },
      });
      // graph.fromJSON(dataObj);
      // graph.centerContent(); //内容居中

      let model = { nodes: [], edges: [] };
      const dagreLayout = new DagreLayout({
        type: "dagre",
        rankdir: "LR",
        align: "",
        ranksep: 230,
        nodesep: 230,
        controlPoints: true,
      });
      const newModel = dagreLayout.layout(model);
      graph.fromJSON(newModel);
      this.graph = graph;
      this.clickAction(); //系统事件
      this.custoAction(); //自定义事件
      this.addDelChangeAction(); //监听添加删除改变事件
      this.moveChangeAction(); //監聽移入移出事件
      this.dataInit();
      mainFn = x6MainFn(graph);

    },
    clickAction() {
      this.graph.on("cell:click", ({ e, x, y, cell, view }) => {
        console.log("cell 节点/边:click", e, x, y, cell, view);
      });
      this.graph.on("node:click", ({ e, x, y, node, view }) => {
        console.log("node 节点:click", e, x, y, node, view);
        this.graph.select(node);
      });
      this.graph.on("edge:click", ({ e, x, y, edge, view }) => {
        console.log("	edge 边:click", e, x, y, edge, view);
      });
      this.graph.on("blank:click", ({ e, x, y }) => {
        console.log("blank 画布空白区域:click", e, x, y);
      });
    },
    custoAction() {
      //自定义事件
      this.graph.on("node:delete", ({ view, e }) => {
        console.log("view, e ", view, e);
        e.stopPropagation();
        view.cell.remove();
      });
      this.graph.on("node:customevent", ({ name, view, e }) => {
        console.log("name, view, e ", name, view, e);
        if (name === "del_me") {
          e.stopPropagation();
          view.cell.remove();
        }
      });
    },
    addDelChangeAction() {
      //监听添加删除改变事件
      this.graph.on("node:added", ({ node, index, options }) => {
        console.log("node:added  node, index, options", node, index, options);
      });
      this.graph.on("node:removed", ({ node, index, options }) => {
        console.log("node:removed  node, index, options", node, index, options);
      });
      this.graph.on("node:changed", ({ node, options }) => {
        console.log("node:changed  node,  options", node, options);
      });

      this.graph.on("edge:added", ({ edge, index, options }) => {
        console.log("edge:added  edge, index, options", edge, index, options);
      });
      this.graph.on("edge:removed", ({ edge, index, options }) => {
        console.log("edge:removed  edge, index, options", edge, index, options);
      });
      this.graph.on("edge:changed", ({ edge, options }) => {
        console.log("edge:changed  edge,  options", edge, options);
      });
    },
    //監聽移入移出事件
    moveChangeAction() {
      this.graph.on("node:mouseenter", ({ e, node, view }) => {
        // console.log("node:mouseenter e, node, view", e, node, view);
        if (node.data.type == "tool") {
          node.addTools([
            {
              name: "button-remove",
              args: { x: 10, y: 16 },
            },
          ]);
        }
      });
      this.graph.on("node:mouseleave", ({ e, node, view }) => {
        // console.log("node:mouseleave  e, node, view", e, node, view);
        if (node.hasTool("button-remove")) {
          node.removeTool("button-remove");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/components/mod/style/actionMod.css";
@import "@/components/mod/style/main.css";
@import "@/components/mod/style/tabMod.css";
#container8 {
  width: 100%;
  height: 500px;
}
</style>